class BasicData {
    constructor() {
        this._initData();
        this.houseId = fxj.getSearch().get('houseId');
    }

    saveCurrentInput(data) {
        this.id = setInterval(() => {
            localStorage.setItem('hm_basic', JSON.stringify(data));
        }, 2000);
    }

    _initData() {
        this.data = (() => {
            return JSON.parse(localStorage.getItem('hm_basic')) || {
                selectedFacility: '',
                facility_all: [],
                facility_list: [],
                location: 0, //地址页显示
                add_address_page: 0,
                step2: 0,
                mainpage: 0, //主菜单页显示
                pictureGuid: 0, //图片引导页
                setPicture: 0, //图片设置页
                stepnow: 0, //当前页面
                basic: 1, //基础信息页面
                infrastructure: 0, //基础设施
                introduce: 0, //介绍页
                setIntroduce: 0, //介绍页显示
                bedamount: 0,
                img_rotate: {
                    transform: '',
                },
                succese_page: 0,

                address_list: {},

                send_imgdata: {},
                token: localStorage.token,
                add_address: {
                    adcode: '',
                    street: '',
                    houseNumber: '',
                    detailAddress: '',
                    lng: '',
                    lat: '',
                    token: localStorage.token,
                },

                stepone_send: {
                    roomType: '',
                    roomTypeText: '请选择',
                    roomIndoors: '',
                    roomHalls: '',
                    roomKitchens: '',
                    roomToilets: '',
                    roomVeranda: '',
                    houseClassify: '',
                    addGuest: 0,
                    addBed: 0,
                    houseArea: '',
                    toiletType: 0,
                    token: localStorage.token,
                    houseAddress: '',
                    houseTitle: '',
                    rentType: -1,
                    rentTypeText: '请选择',
                    bedLinen: 0,
                    other: '',
                    appliance: [],
                    bedList: [],
                    houseId: '',
                },
                basic_info: { //基础信息数据
                    bedinfo: {
                        width: '',
                        length: '',
                        count: '',
                    },
                    bedtype: '请选择',
                    city_name: '',
                    rent_type: 0,
                    house_location: 0,
                    house_area: '',
                    house_type: 0,
                    house_unit: 0,
                    people_max: 0,
                    bed_amount: 0,
                    basic_thing: 0,
                    tolet_type: 0,
                    add_bed: 0,
                    change_sheet: 0,
                    add_person: 0,
                    province_block: '',
                    city_area: '',
                    city_ajax_data: '',
                },

                bedSet: { //床位设置页面控制
                    page1: 0,
                    page2: 0,
                    changeBed: 0,
                },
                text_content: '',
                textarea_number_max: 0,
                addressTxt: '请选择',
            };
        })();
        // 滤重
        this.data.stepone_send.appliance = [...new Set(this.data.stepone_send.appliance)];
        // 为选中设施添加开关打开的样式
        if (this.data.stepone_send.appliance.length > 0) {
            const facilitys = document.querySelectorAll('.she-shi');
            forEach(facilitys, (el) => {
                if (this.data.stepone_send.appliance.includes(el.getAttribute('data-value'))) {
                    el.nextElementSibling.classList.add('mui-active');
                }
            });
        }
        if (isExist(this.data.stepone_send.roomIndoors)) {
            const info = this.data.stepone_send;
            $('#housetype')
                .text(`${info.roomIndoors}室${info.roomHalls}厅${info.roomToilets}卫${info.roomKitchens}厨${info.roomVeranda}阳台`);
        }
    }
}

class BdMap {
    constructor() {
        this.map = {
            mapContext: null,
            decoder: null,
            point: null,
            marker: null,
        };
    }

    init() {
        const map = new BMap.Map('map'); // 创建Map实例
        this.map.mapContext = map;
        this.map.decoder = new BMap.Geocoder();
        map.enableScrollWheelZoom(); //启用滚轮放大缩小

        const myGeo = new BMap.Geocoder();
        // 将地址解析结果显示在地图上,并调整地图视野
        myGeo.getPoint('成都市', function (point) {
            if (point) {
                map.centerAndZoom(point, 13);
            }
            else {
                toast('您选择地址没有解析到结果!');
            }
        }, '成都市');

        new BMap.NavigationControl({
            type: BMAP_NAVIGATION_CONTROL_LARGE,
            enableGeolocation: true,
        });
    }
}

class BasicPicker {
    constructor() {
        this.initBedPicker();
        this.initHouseTypePicker();
        this.initCityAreaPicker();
        this.initHouseType();
        this.initRentType();
    }

    initBedPicker() {
        const bed = [
            {
                value: '1',
                text: '双人床',
            },
            {
                value: '2',
                text: '单人床',
            },
            {
                value: '3',
                text: '上下铺',
            },
            {
                value: '4',
                text: '沙发',
            },
            {
                value: '5',
                text: '榻榻米',
            },
            {
                value: '6',
                text: '其他',
            },
        ];
        const housearea = new Picker({
            data: [bed],
            title: '床铺类型',
        });
        document.getElementById('bed_kind').addEventListener('click', () => {
            housearea.show();
        });
        housearea.on('picker.valuechange', function (selectedVal, selectedIndex) {
            ja.basic_info.bedinfo.type = bed[selectedIndex].value;
            ja.basic_info.bedinfo.bedtype = bed[selectedIndex].value;
            ja.basic_info.bedtype = bed[selectedIndex].text;
            ja.basic_info.bedinfo.bedName = bed[selectedIndex].text;
        });
    }

    initHouseTypePicker() {
        const houseTypeBtn = document.getElementById('housetype');
        const getOptions = (unit = '', amount = 20, min = 0) => {
            let tempOptions = [];
            for (let i = min; i <= amount; i++) {
                tempOptions.push({
                    value: i.toString(),
                    text: i.toString() + unit,
                });
            }
            return tempOptions;
        };

        const s = getOptions('室', 20, 1);
        const t = getOptions('厅');
        const w = getOptions('卫');
        const c = getOptions('厨');
        const yt = getOptions('阳台');

        const houseTypePicker = new Picker({
            data: [s, t, w, c, yt],
            title: '房屋户型',
        });

        houseTypePicker.on('picker.valuechange', function (selectedVal, selectedIndex) {
            ja.stepone_send.roomIndoors = s[selectedIndex[0]].value;
            ja.stepone_send.roomHalls = t[selectedIndex[1]].value;
            ja.stepone_send.roomToilets = w[selectedIndex[2]].value;
            ja.stepone_send.roomKitchens = c[selectedIndex[3]].value;
            ja.stepone_send.roomVeranda = yt[selectedIndex[4]].value;
            document.getElementById('housetype').innerHTML = s[selectedIndex[0]].text + t[selectedIndex[1]].text + w[selectedIndex[2]].text + c[selectedIndex[3]].text + yt[selectedIndex[4]].text;
        });
        houseTypeBtn.addEventListener('click', () => {
            houseTypePicker.show();
        });
    }

    async initCityAreaPicker() {
        const cityArea = new City();
        const nationEl = document.getElementById('house_area');
        const picker = new Picker({
            data: [cityArea.province, cityArea.city, cityArea.county],
            selectedIndex: [0, 0, 0],
            title: '选择地区',
        });

        picker.on('picker.change', (index, selectedIndex) => {
            if (index === 0) {
                picker.refillColumn(1, cityArea.getCityByProvince({index: selectedIndex}));
                picker.refillColumn(2, cityArea.county);
            }
            else if (index === 1) {
                picker.refillColumn(2, cityArea.getCountyByCity({index: selectedIndex}));
            }
        });

        picker.on('picker.valuechange', (selectedVal, selectedIndex) => {
            ja.add_address.adcode = cityArea.county[selectedIndex[2]].value;
            ja.basic_info.province_block = cityArea.province[selectedIndex[0]].text + cityArea.city[selectedIndex[1]].text + cityArea.county[selectedIndex[2]].text;
            if (isExist(selectedIndex[2])) {
                ja.getcity(cityArea.county[selectedIndex[2]].value);
                const myGeo = new BMap.Geocoder();
                // 将地址解析结果显示在地图上,并调整地图视野
                myGeo.getPoint(ja.basic_info.province_block, function (point) {
                    if (point) {
                        bdmap.map.mapContext.centerAndZoom(point, 13);
                    }
                    else {
                        toast('您选择地址没有解析到结果!');
                    }
                }, ja.basic_info.province_block);
            }
        });

        nationEl.addEventListener('click', () => {
            if (!isExist(bdmap.map.mapContext)) {
                bdmap.init();
            }
            picker.show();
        });
    }

    initHouseType() {
        const nationEl = document.getElementById('house_type');
        const type = [
            {
                value: '1',
                text: '民居',
            },
            {
                value: '2',
                text: '公寓',
            },
            {
                value: '3',
                text: '别墅',
            },
            {
                value: '4',
                text: '客栈',
            },
            {
                value: '5',
                text: '复式',
            },
            {
                value: '6',
                text: '农家乐',
            },
            {
                value: '7',
                text: '四合院',
            },
            {
                value: '8',
                text: '老洋房',
            },
        ];
        const picker = new Picker({
            data: [type],
            selectedIndex: [0],
            title: '房源类型',
        });

        picker.on('picker.valuechange', (selectedVal, selectedIndex) => {
            ja.stepone_send.roomType = type[selectedIndex[0]].value;
            ja.stepone_send.roomTypeText = type[selectedIndex[0]].text;
        });

        nationEl.addEventListener('click', () => {
            picker.show();
        });
    }

    initRentType() {
        const nationEl = document.getElementById('rent_type');
        const type = [{
            value: '0',
            text: '整套出租',
        }, {
            value: '1',
            text: '单间出租',
        },];
        const picker = new Picker({
            data: [type],
            selectedIndex: [0],
            title: '出租类型',
        });

        picker.on('picker.valuechange', (selectedVal, selectedIndex) => {
            ja.stepone_send.rentType = Number(type[selectedIndex[0]].value);
            ja.stepone_send.rentTypeText = type[selectedIndex[0]].text;
            document.getElementById('rent_type').innerHTML = ja.stepone_send.rentTypeText;
        });

        nationEl.addEventListener('click', () => {
            picker.show();
        });
    }
}

const basicData = new BasicData();
const bdmap = new BdMap();

const ja = new Vue({
    el: '#main',
    data: basicData.data,
    methods: {
        toBasic() {
            this.basic = 1;
            this.mainpage = 0;
            this.location = 0;
            this.infrastructure = 0;
        },
        toLocation() {
            this.basic = 0;
            this.location = 1;
            this.stepnow = 5;
            this.add_address_page = 0;
        },
        toInfrastructure() {
            this.basic = 0;
            this.infrastructure = 1;
            this.stepnow = 5;
        },
        bedPage(type, bed, i) {
            switch (type) {
                case 1:
                    this.bedSet.page2 = 0;
                    this.bedSet.page1 = 1;
                    this.bedSet.changeBed = 0;
                    break;
                case 2:
                    this.bedSet.page1 = 0;
                    this.bedSet.page2 = 1;
                    this.bedSet.changeBed = 0;
                    ja.basic_info.bedinfo.count = '';
                    ja.basic_info.bedinfo.width = '';
                    ja.basic_info.bedinfo.length = '';
                    ja.basic_info.bedinfo.bedtype = '1';
                    ja.basic_info.bedinfo.bedName = '双人床';
                    break;
                case 3:
                    this.bedSet.page1 = 0;
                    this.bedSet.page2 = 0;
                    this.bedSet.changeBed = 0;
                    this.basic = 1;
                    return;
                case 4:
                    ja.basic_info.bedtype = bed.bedName;
                    ja.basic_info.bedinfo.count = bed.count;
                    ja.basic_info.bedinfo.width = bed.width;
                    ja.basic_info.bedinfo.length = bed.length;
                    ja.basic_info.bedinfo.bedtype = bed.bedtype;
                    ja.basic_info.bedinfo.bedName = bed.bedName;
                    ja.basic_info.__bedIndex = i;
                    this.bedSet.page1 = 0;
                    this.bedSet.page2 = 1;
                    this.bedSet.changeBed = 1;
                    break;
            }
            this.basic = 0;
        },
        async send_stepone_send() {
            const close = fxj.dialog.loading({noBg: true});
            ja.stepone_send.bedList.forEach(bed => {
                bed.type = bed.bedtype;
            });
            ja.stepone_send.appliance = (() => {
                // 获取所有选中的设施
                const allFacility = document.querySelectorAll('.she-shi');
                return [...allFacility].map(el => {
                    if ([...el.nextElementSibling.classList].includes('mui-active')) {
                        return el.getAttribute('data-value');
                    }
                }).filter(el => {
                    return isExist(el);
                });
            })();
            const re = await ajax({
                url: `home/${fxj.getSearch()
                    .get('type') === 'add' ? 'HouseUpload/infoAdd' : 'houseManage/houseUpdateInfo'}`,
                data: {
                    data: JSON.stringify(ja.stepone_send),
                },
            });
            close();
            if (re.err === 0) {
                if (fxj.getSearch().get('type') === 'add') {
                    clearInterval(basicData.id);
                    localStorage.removeItem('hm_basic');
                }
                await toast('提交成功');
                if (fxj.getSearch().get('papa') === 'menu') {
                    history.back();
                }
                else {
                    goPage('hm_introduce.html', {
                        data: {
                            houseId: re.data.houseId,
                            type: fxj.getSearch().get('type'),
                        },
                    });
                }
            }
            else {
                toast(re.msg);
            }
        },
        async send_address() {
            if (!this.add_address.street) {
                toast('请拖动地图并点击按钮选择街道');
                return;
            }
            if (!this.add_address.houseNumber) {
                toast('请填写门牌号码');
                return;
            }
            if (!this.add_address.detailAddress) {
                toast('请填写详细地址');
                return;
            }

            const re = await ajax({
                url: 'Home/HouseUpload/addAddress',
                data: {
                    street: this.add_address.street,
                    houseNumber: this.add_address.houseNumber,
                    detailAddress: this.add_address.detailAddress,
                    lng: this.add_address.lng,
                    lat: this.add_address.lat,
                    token: this.add_address.token,
                    adcode: this.add_address.adcode,
                },
            });

            if (re.err === 0) {
                ja.stepone_send.houseAddress = re.data.id;
                ja.add_address_Fun();
                ja.address_list[re.data.id] = {
                    mes: ja.add_address.detailAddress,
                    id: re.data.id,
                    active: true,
                };
                ja.setAddressId(re.data.id, ja.add_address.detailAddress);
                toast('添加地址成功');
            }
            else {
                toast(re.msg);
            }
        },

        mapchose() {
            if (!isExist(bdmap.map.mapContext)) {
                bdmap.init();
            }
            //百度地图
            const center = bdmap.map.mapContext.getCenter();
            ja.add_address.lat = center.lat;
            ja.add_address.lng = center.lng;

            $.ajax({
                'url': 'http://api.map.baidu.com/geocoder/v2/',
                'data': {
                    location: ja.add_address.lat + ',' + ja.add_address.lng,
                    output: 'json',
                    ak: 'j70AyjKaBB4euD5THDXZfNfLAl2wn22i',
                },
                'async': false,
                'dataType': 'jsonp',
                'jsonp': 'callback',
                'jsonpCallback': 'renderReverse',
                'success': (data) => {
                    const {location, addressComponent, sematic_description} = data.result;
                    ja.add_address.lat = location.lat;
                    ja.add_address.lng = location.lng;
                    ja.add_address.street = addressComponent.street || sematic_description;
                },
                'error': data => {
                    console.error(data);
                    toast('网络连接异常，请稍后重试');
                },
            });
        },
        async getcity(e) {
            const result = await ajax({
                url: '/home/index/getDistrict',
                type: 'post',
                data: {
                    'cityCode': e,
                },
            });
            ja.basic_info.city_ajax_data = result.data;
        },
        getInfrastructure() {
            $('span[data-value]').each(function () {
                const isActive = $(this).parent().find('div').hasClass('mui-active');
                if (isActive) {
                    ja.stepone_send.appliance.push($(this).attr('data-value'));
                    ja.stepone_send.appliance = [...new Set(ja.stepone_send.appliance)];
                    ja.selectedFacility = ja.stepone_send.appliance.length;
                }
            });
            this.toBasic();
        },
        addClints() {
            if ($('#addClints').hasClass('mui-active')) {
                ja.stepone_send.addGuest = 1;
            }
            else {
                ja.stepone_send.addGuest = 0;
            }
        },
        isaddbed() {
            if ($('#addbed').hasClass('mui-active')) {
                ja.stepone_send.addBed = 1;
            }
            else {
                ja.stepone_send.addBed = 0;
            }
        },
        addBedFun() {
            let ok = true;
            forEach(Object.keys(this.basic_info.bedinfo), key => {
                if (!isExist(this.basic_info.bedinfo[key])) {
                    ok = false;
                }
            });
            if (!ok) {
                toast('请完善床位信息');
                return;
            }
            this.stepone_send.bedList.push(Object.assign({}, this.basic_info.bedinfo));
            this.bedamount = parseInt(this.bedamount) + parseInt(this.basic_info.bedinfo.count) + '张';
            this.bedPage(1);
        },
        changeBedFun() {
            ja.stepone_send.bedList[ja.basic_info.__bedIndex] = JSON.parse(JSON.stringify(this.basic_info.bedinfo));
            this.bedPage(1);
        },
        delBed() {
            ja.stepone_send.bedList[ja.basic_info.__bedIndex] = null;
            ja.stepone_send.bedList = ja.stepone_send.bedList.filter(bed => {
                return isExist(bed);
            });
            this.bedamount = ja.stepone_send.bedList.reduce((num, bed) => num + Number(bed.count), 0);
            this.bedamount = this.bedamount ? this.bedamount + '张' : 0;
            this.bedPage(1);
        },
        toadd_addressmain() {
            this.add_address_page = 0;
        },
        toadd_address() {
            bdmap.init();
            this.add_address_page = 1;
            this.toadd_address = () => {
                this.add_address_page = 1;
            };
        },
        add_address_Fun() {
            this.add_address_page = 0;
        },
        setAddressId(id, mes) {
            let houseAddress = ja.address_list[ja.stepone_send.houseAddress];
            if (houseAddress) {
                houseAddress.active = false;
            }
            ja.stepone_send.houseAddress = id;
            ja.address_list[id].active = true;
            ja.$forceUpdate();
            ja.addressTxt = mes;
        },
        delAddress(id) {
            delete ja.address_list[id];
            const tempObj = Object.assign({}, ja.address_list);
            ja.address_list = tempObj;
        },
    },
});

async function created() {
    reqAddressList();
    if (fxj.getSearch().get('type') === 'add') return;
    ja.stepone_send.houseId = basicData.houseId;
    const re = await ajax({
        url: 'home/houseDetail/getHouseDetail',
        data: {
            houseId: basicData.houseId,
        },
    });
    if (re.err !== 0) {
        toast(re.msg);
        return;
    }
    const {facility, other, title, aid} = re.data;
    // 为选中设施添加开关打开的样式
    ja.facility_list = facility.map(facility => {
        return facility.facility_id;
    });
    const facilities = document.querySelectorAll('.she-shi');
    forEach(facilities, (el) => {
        if (ja.facility_list.includes(el.getAttribute('data-value'))) {
            el.nextElementSibling.classList.add('mui-active');
        }
    });
    ja.facility_all = facility;
    ja.stepone_send.other = other;
    ja.stepone_send.houseTitle = title;
    ja.stepone_send.houseAddress = aid;
    let addressHouse = ja.address_list[aid];
    if (addressHouse) {
        addressHouse.active = true;
    }

    const {lease_type, lease_id, house_type, house_type_id, address_detail, area} = re.data;
    ja.stepone_send.rentTypeText = lease_type;
    ja.stepone_send.rentType = lease_id;
    ja.stepone_send.roomTypeText = house_type;
    ja.stepone_send.roomType = house_type_id;
    ja.addressTxt = address_detail;
    ja.stepone_send.houseArea = area;

    const {bedroom, hall, kitchen, bathroom, balcony, people, people_add, bed_add, toilet_independent, sheet, bed} = re.data;
    ja.stepone_send.roomIndoors = bedroom;
    ja.stepone_send.roomHalls = hall;
    ja.stepone_send.roomKitchens = kitchen;
    ja.stepone_send.roomToilets = bathroom;
    ja.stepone_send.roomVeranda = balcony;
    $('#housetype').text(`${bedroom}室${hall}厅${kitchen}厨${bathroom}卫${balcony}阳台`);
    ja.stepone_send.houseClassify = people;

    if (people_add === '能加客') {
        ja.stepone_send.addGuest = 1;
    }
    else {
        ja.stepone_send.addGuest = 0;
    }
    ja.stepone_send.addBed = bed_add;

    ja.stepone_send.toiletType = toilet_independent;
    if (ja.stepone_send.toiletType === '独立卫生间') {
        ja.stepone_send.toiletType = 1;
    }
    else {
        ja.stepone_send.toiletType = 0;
    }

    ja.stepone_send.token = localStorage.token;

    ja.stepone_send.bedLinen = sheet;
    if (ja.stepone_send.bedLinen === '每客一换') {
        ja.stepone_send.bedLinen = 0;
    }
    else {
        ja.stepone_send.bedLinen = 1;
    }
    forEach(re.data.facility, facility => {
        ja.stepone_send.appliance.push(facility.facility_id);
    });
    ja.stepone_send.appliance = [...new Set(ja.stepone_send.appliance)];
    ja.selectedFacility = ja.stepone_send.appliance.length;
    forEach(bed.list, bed => {
        ja.stepone_send.bedList.push({
            bedName: bed.name,
            width: bed.width,
            length: bed.length,
            count: bed.amount,
            bedtype: bed.type_id,
        });
    });
    ja.bedamount = bed.count ? bed.count + '张' : 0;
}

function apiready() {
    created();
}

if (fxj.getSearch().get('type') === 'add') {
    basicData.saveCurrentInput(ja.$data);
}
new BasicPicker();

async function reqAddressList() {
    const res = await ajax({
        url: '/home/houseManage/getUserAddressList',
        type: 'post',
        contentType: 'application/x-www-form-urlencoded',
        data: {
            token: localStorage.token,
        },
    });
    forEach(res.data, (temp) => {
        const {address_detail, number_door, aid} = temp;
        ja.address_list[temp.aid] = {
            mes: address_detail + number_door,
            id: aid,
            active: false,
        };
    });
}

function back() {
    if (fxj.getSearch().get('papa') === 'menu') {
        const houseId = fxj.getSearch().get('houseId');
        location.replace(`hm_menu.html?houseId=${houseId}&type=alter`);
    }
    else {
        fxj.closeWin();
    }
}

function checkAreaLegal() {
    if (ja.stepone_send.houseArea === '') return;
    const area = +ja.stepone_send.houseArea;
    if (area < 1 || area > 9999) {
        toast('房屋面积应在1 ~ 9999');
    }
}
